package com.yuyu.shop.infrastructure.general.mq.listener;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuyu.commons.constant.BaseConstant;
import com.yuyu.shop.domain.order.DO.OrderDO;
import com.yuyu.shop.infrastructure.persistence.mapper.SecKillOrderMapper;
import com.yuyu.shop.infrastructure.persistence.po.SecKillOrderPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author
 * @version 1.0
 * @description: 订单是否在规定时间内支付,并返回库存(注:因为是开源的 所以延时发送并不能生效,需要购买商用版本)
 * @date 2022/10/13 14:34
 */
@Slf4j
@Component
public class OnsDelayBackOrderListener implements MessageListener {

    @Resource
    private SecKillOrderMapper secKillOrderMapper;

//    @Resource
//    private StockCache stockCache;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        String secKill = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("接受的时间为{}",System.currentTimeMillis());
        try {
            OrderDO orderDO = JSON.parseObject(secKill, OrderDO.class);
            SecKillOrderPO secKillOrderPO = secKillOrderMapper.selectOne(new LambdaQueryWrapper<SecKillOrderPO>()
                    .eq(SecKillOrderPO::getOrderId, orderDO.getOrderId()));
            if (BaseConstant.TWO > secKillOrderPO.getStatus()) {
//                //代表并未付款 返回库存
//                stockCache.increaseStock(orderDO.getGoodId(), orderDO.getGoodsNum().longValue());
//                log.info("订单id为{}未在指定时间内支付,返回商品id为{}的{}个库存",orderDO.getOrderId(),orderDO.getGoodId(),orderDO.getGoodsNum());
            }
            return Action.CommitMessage;
        }catch (Exception e){
            log.error("查询订单状态消息处理失败!",e);
            return Action.ReconsumeLater;
        }

    }
}
